package com.fishcoco.app.yunhang.activity.login;

import android.content.Intent;
import android.support.design.widget.TextInputEditText;
import android.support.design.widget.TextInputLayout;
import android.support.v7.widget.CardView;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.view.animation.AccelerateDecelerateInterpolator;
import android.view.animation.AlphaAnimation;
import android.view.animation.AnimationSet;
import android.view.animation.TranslateAnimation;

import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.RegexUtils;
import com.blankj.utilcode.util.SPUtils;
import com.blankj.utilcode.util.StringUtils;
import com.fishcoco.app.yunhang.R;
import com.fishcoco.app.yunhang.activity.base.BaseActivity;
import com.fishcoco.app.yunhang.entity.LoginResponseBody;
import com.fishcoco.app.yunhang.entity.UniverResponseBody;
import com.fishcoco.app.yunhang.entity.YHRequestBody;
import com.fishcoco.app.yunhang.utils.constant.ConstantUtil;
import com.fishcoco.app.yunhang.utils.encryp.SymmetricEncoder3;
import com.fishcoco.app.yunhang.utils.gsonnull.NullStringToEmptyAdapterFactory;
import com.fishcoco.app.yunhang.utils.retrofit.RetrofitClient;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.tamic.novate.Novate;
import com.tamic.novate.Throwable;
import com.tamic.novate.callback.RxStringCallback;
import com.tamic.novate.util.LogWraper;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.Map;

import okhttp3.RequestBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

import static com.fishcoco.app.yunhang.utils.constant.ConstantUtil.SP_KEY_APPNAME;
import static com.fishcoco.app.yunhang.utils.constant.ConstantUtil.SP_KEY_MACADDR;
import static com.fishcoco.app.yunhang.utils.constant.ConstantUtil.SP_KEY_PHONE;
import static com.fishcoco.app.yunhang.utils.constant.ConstantUtil.SP_KEY_TOKEN;
import static com.fishcoco.app.yunhang.utils.constant.ConstantUtil.SP_KEY_USERNAME;

/**
 * A login screen that offers login via email/password.
 */
public class LoginActivity extends BaseActivity {

    // UI references.
    private CardView cvLogin;
    private CardView cvRegister;
    private TextInputEditText phoneNumberForLoginET;
    private TextInputLayout phoneNumberForLoginTIL;
    private TextInputEditText passwordForLoginET;
    private TextInputLayout passwordForLoginTIL;
    private TextInputEditText phoneNumberForRegisterET;
    private TextInputLayout phoneNumberForRegisterTIL;
    private TextInputEditText passwordForRegisterET;
    private TextInputLayout passwordForRegisterTIL;
    private TextInputEditText repeatPasswordForRegisterET;
    private TextInputLayout repeatPasswordForRegisterTIL;

    private AnimationSet outAnimSet;
    private AnimationSet inAnimSet;

    private Novate novate;

    @Override
    protected int setLayoutResourceID() {
        return R.layout.activity_login;
    }

    @Override
    protected void setUpView() {
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        phoneNumberForLoginET = $(R.id.et_username_login);
        passwordForLoginET = $(R.id.et_password_login);
        phoneNumberForLoginTIL = $(R.id.et_username_login_til);
        passwordForLoginTIL = $(R.id.et_password_login_til);
        phoneNumberForRegisterET = $(R.id.et_username_register);
        phoneNumberForRegisterTIL = $(R.id.et_username_register_til);
        passwordForRegisterET = $(R.id.et_password_register);
        passwordForRegisterTIL = $(R.id.et_password_register_til);
        repeatPasswordForRegisterET = $(R.id.et_repeat_password_register);
        repeatPasswordForRegisterTIL = $(R.id.et_repeat_password_register_til);


        cvLogin = $(R.id.cv_login);
        cvRegister = $(R.id.cv_register);

        initClickListener(R.id.iv_register_close,R.id.bt_show_register,R.id.bt_register,R.id.bt_login,R.id.bt_skip);
    }

    @Override
    protected void setUpData() {
        super.setUpData();
        novate = new Novate.Builder(this)
                .connectTimeout(20)
                .writeTimeout(15)
                .baseUrl(ConstantUtil.API_BASE_URL)
                .addLog(true)
                .build();
    }

    @Override
    public void onClick(View v) {
        super.onClick(v);
        switch (v.getId())
        {
            case R.id.bt_show_register:
                viewsUseAnimShow(cvLogin,cvRegister);
                break;
            case R.id.bt_login:
                attemptLogin();
                break;
            case R.id.bt_register:
                attemptRegister();
                break;
            case R.id.iv_register_close:
                viewsUseAnimShow(cvRegister,cvLogin);
                break;
            case R.id.bt_skip:
                startActivity(new Intent(LoginActivity.this, MainActivity.class));
                finish();
                break;
        }
    }

    private void attemptLogin() {
        if (!StringUtils.isTrimEmpty(phoneNumberForLoginET.getText().toString().trim()))
        {
            phoneNumberForLoginTIL.setErrorEnabled(false);
            if (RegexUtils.isMobileExact(phoneNumberForLoginET.getText().toString().trim()))
            {
                phoneNumberForLoginTIL.setErrorEnabled(false);
                if (!StringUtils.isTrimEmpty(passwordForLoginET.getText().toString().trim()))
                {
                    if (passwordForLoginET.getText().toString().length()>=5&& passwordForLoginET.getText().toString().length()<=16)
                    {
                        passwordForLoginTIL.setErrorEnabled(false);
                        phoneNumberForLoginTIL.setErrorEnabled(false);
                        login(phoneNumberForLoginET.getText().toString().trim(), passwordForLoginET.getText().toString().trim());

                    } else {
                        passwordForLoginTIL.setError("密码长度5~16位");
                    }

                } else {
                    passwordForLoginTIL.setError("请输入密码");
                }

            } else {
                phoneNumberForLoginTIL.setError("请输入合法的手机号");
            }

        } else {
            phoneNumberForLoginTIL.setError("请输入手机号");
        }
    }

    private void attemptRegister() {
        String username = phoneNumberForRegisterET.getText().toString().trim();
        String password = passwordForRegisterET.getText().toString().trim();
        String repeatPassword = repeatPasswordForRegisterET.getText().toString().trim();

        if (!StringUtils.isTrimEmpty(username))
        {
            phoneNumberForRegisterTIL.setErrorEnabled(false);
            if (RegexUtils.isMobileExact(username))
            {
                if (!StringUtils.isTrimEmpty(password))
                {
                    if (password.length()>=5&&password.length()<=16)
                    {
                        passwordForRegisterTIL.setErrorEnabled(false);
                        if (repeatPassword.equals(password))
                        {
                            phoneNumberForRegisterTIL.setErrorEnabled(false);
                            passwordForRegisterTIL.setErrorEnabled(false);
                            repeatPasswordForRegisterTIL.setErrorEnabled(false);
                            register(username,password);
                        } else {
                            repeatPasswordForRegisterTIL.setError("两次密码不同");
                        }
                    } else {
                        passwordForRegisterTIL.setError("密码长度5~16位");
                    }
                } else {
                    passwordForRegisterTIL.setError("请输入密码");
                }
            } else {
                phoneNumberForRegisterTIL.setError("请输入合法的手机号");
            }
        } else {
            phoneNumberForRegisterTIL.setError("请输入手机号");
        }
    }


    private void login(String username,String password) {
        loadingDialog(getString(R.string.login_start));
        JSONObject jo = new JSONObject();
        try {
            jo.put("phone",username);
            jo.put("password",password);
            jo.put("uuid","a3s34al4dc4l2lslk4bwlne23A");
        } catch (JSONException e) {
            e.printStackTrace();
        }
        LogUtils.d("jo:"+jo.toString());
        String encodeResult1 = SymmetricEncoder3.AESEncode(null,jo.toString());

        YHRequestBody body = new YHRequestBody();
        body.setRequestData(encodeResult1);
        String route = new Gson().toJson(body);

        novate.rxJson(ConstantUtil.API_URL_LOGIN, route, new RxStringCallback() {

            @Override
            public void onProgress(Object tag, float progress, long transfered, long total) {
                super.onProgress(tag, progress, transfered, total);
            }

            @Override
            public void onStart(Object tag) {
                super.onStart(tag);
            }

            @Override
            public void onError(Object tag, Throwable e) {
                loadingDialog(e.getMessage());
            }

            @Override
            public void onCancel(Object tag, Throwable e) {

            }

            @Override
            public void onNext(Object tag, String response) {
                LogWraper.d(response);
                if (response!=null) {
                    String result = SymmetricEncoder3.AESDncode(null, response);
                    LogUtils.d("result:" + result);
                    Gson gs = new Gson();
                    Map<String, Object> map = gs.fromJson(result, Map.class);
                    Number resultCode = (Number) map.get("result");
                    LogUtils.d("resultCode:" + resultCode.intValue());
                    if (resultCode.intValue() == 1) {
                        LogUtils.d("resultMsg:" + map.get("msg"));
                        toast("" + map.get("msg"));
                        loadingDialog(""+map.get("msg"));
                    } else {
                        Gson gson = new GsonBuilder().registerTypeAdapterFactory(new NullStringToEmptyAdapterFactory()).create();
                        LoginResponseBody responseBody = gson.fromJson(result, LoginResponseBody.class);
                        LogUtils.d("responseBody:" + responseBody.toString());
                        toast(responseBody.getToken());
                        LogUtils.d("token:" + responseBody.getToken());
                        ConstantUtil.GET_ACCESS_TOKEN = responseBody.getToken();
                        SPUtils.getInstance(SP_KEY_APPNAME).put(SP_KEY_TOKEN, responseBody.getToken());
                        SPUtils.getInstance(SP_KEY_APPNAME).put(SP_KEY_PHONE, responseBody.getPhone());
                        SPUtils.getInstance(SP_KEY_APPNAME).put(SP_KEY_USERNAME, responseBody.getUserName());
                        startActivity(new Intent(LoginActivity.this, MainActivity.class));
                        finish();
                    }
                }
            }


        });
    }

    private void register(String username,String password) {
        String macAddr = SPUtils.getInstance(SP_KEY_APPNAME).getString(SP_KEY_MACADDR);
        JSONObject jo = new JSONObject();
        try {
            jo.put("phone",username);
            jo.put("password",password);
            jo.put("uuid",macAddr);
        } catch (JSONException e) {
            e.printStackTrace();
        }

        String encodeResult1 = SymmetricEncoder3.AESEncode(null,jo.toString());

        YHRequestBody body = new YHRequestBody();
        body.setRequestData(encodeResult1);
        String route = new Gson().toJson(body);
        RequestBody requestBody= RequestBody.create(okhttp3.MediaType.parse("application/json; charset=utf-8"),route);
        RetrofitClient.getInstance(this).createServiceReturnString()
                .register(requestBody)
                .enqueue(new Callback<String>() {
                    @Override
                    public void onResponse(Call<String> call, Response<String> response) {

                        if (response.body()!=null) {
                            String result = SymmetricEncoder3.AESDncode(null, response.body());
                            LogUtils.d("result:" + result);
                            Gson gs = new  Gson();
                            Map<String,Object> map = gs.fromJson(result, Map.class);
                            Number resultCode = (Number)map.get("result");
                            LogUtils.d("resultCode:" + resultCode.intValue());
                            if (resultCode.intValue()==1)
                            {
                                LogUtils.d("resultMsg:" + map.get("msg"));
                            } else {
                                Gson gson  = new GsonBuilder().registerTypeAdapterFactory(new NullStringToEmptyAdapterFactory()).create();
                                UniverResponseBody responseBody = gson.fromJson(result,UniverResponseBody.class);
                                LogUtils.d("responseBody:" + responseBody.toString());
                            }
                        }
                    }

                    @Override
                    public void onFailure(Call<String> call, java.lang.Throwable t) {
                        LogUtils.d("error:"+t.toString());
                    }

                });
    }

    private void viewsUseAnimShow(View outView,View inView)
    {
        outView.startAnimation(getOutAnimSet());
        inView.setVisibility(View.INVISIBLE);
        inView.bringToFront();
        inView.startAnimation(getInAnimSet());
    }

    private AnimationSet getInAnimSet() {
        if (inAnimSet==null)
        {
            TranslateAnimation tAnim2 = new TranslateAnimation(20, 0, 20, 0);
            AlphaAnimation aAnima2 = new AlphaAnimation(0.5f, 1.0f);
            tAnim2.setDuration(1000);
            aAnima2.setDuration(1000);
            tAnim2.setInterpolator(new AccelerateDecelerateInterpolator());
            aAnima2.setInterpolator(new AccelerateDecelerateInterpolator());
            AnimationSet set2 = new AnimationSet(true);
            set2.setFillAfter(true);
            set2.addAnimation(tAnim2);
            set2.addAnimation(aAnima2);

            inAnimSet = set2;
        }
        return inAnimSet;
    }

    private AnimationSet getOutAnimSet() {
        if (outAnimSet==null)
        {
            TranslateAnimation tAnim = new TranslateAnimation(0, -20, 0, -20);
            AlphaAnimation aAnima = new AlphaAnimation(1.0f, 0.5f);
            tAnim.setDuration(1000);
            aAnima.setDuration(1000);
            tAnim.setInterpolator(new AccelerateDecelerateInterpolator());
            aAnima.setInterpolator(new AccelerateDecelerateInterpolator());
            AnimationSet set = new AnimationSet(true);
            set.setFillAfter(true);
            set.addAnimation(tAnim);
            set.addAnimation(aAnima);

            outAnimSet = set;
        }
        return outAnimSet;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        cvLogin.clearAnimation();
        cvRegister.clearAnimation();
        if (inAnimSet!=null)
        {
            inAnimSet.cancel();
            inAnimSet=null;
        }
        if (outAnimSet!=null)
        {
            outAnimSet.cancel();
            outAnimSet=null;
        }
    }

    private void connectChatroom()
    {

    }
}

